package netService

import (
	"gitee.com/ling-bin/network/netInterface"
	"sync"
	"sync/atomic"
)

//ConnManager 连接管理模块
type ConnManager struct {
	connections sync.Map //连接记录
	count       int32    //连接数
}

//NewConnManager 实例化管理
func NewConnManager() netInterface.IConnManager {
	return &ConnManager{}
}

//Add 添加链接[新连接处理]
func (c *ConnManager) Add(conn netInterface.IConnection) bool{
	connId := conn.GetConnId()
	_,ok := c.connections.LoadOrStore(connId, conn)
	if !ok {
		atomic.AddInt32(&c.count,1)
		//fmt.Println("增加")
		return true
	}
	return false
}

//Remove 删除连接
func (c *ConnManager) Remove(conn netInterface.IConnection) bool {
	connId := conn.GetConnId()
	return c.RemoveById(connId)
}

//RemoveById 删除连接
func (c *ConnManager) RemoveById(connId uint64) bool {
	_,ok := c.connections.LoadAndDelete(connId)
	//fmt.Println("----开始减少")
	if ok {
		atomic.AddInt32(&c.count,-1)
		//fmt.Println("减少")
		return true
	}
	return false
}

//Get 利用ConnID获取链接
func (c *ConnManager) Get(connId uint64) (netInterface.IConnection, bool) {
	load, ok := c.connections.Load(connId)
	if ok {
		return load.(netInterface.IConnection), ok
	}
	return nil, false
}

//Range 遍历连接
func (c *ConnManager) Range(hFunc func(connId uint64, value netInterface.IConnection) bool) {
	c.connections.Range(func(key, value interface{}) bool {
		return hFunc(key.(uint64), value.(netInterface.IConnection))
	})
}

//Count 获取个数
func (c *ConnManager) Count() int32 {
	return c.count
}

//ClearConn 清除并停止所有连接
func (c *ConnManager) ClearConn() {
	c.connections.Range(func(key, value interface{}) bool {
		c.RemoveById(key.(uint64))
		return true
	})
}
